﻿using System.Security.Claims;
using Microsoft.AspNetCore.Http;

namespace Services
{
    public interface ICurrentUser
    {
        UserClaimsModel CurrentUserInfo { get; }
    }

    public class CurrentUser : ICurrentUser
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly ISqlSugarClient _DB;

        public CurrentUser(IHttpContextAccessor _httpContextAccessor,  ISqlSugarClient dB)
        {
            httpContextAccessor = _httpContextAccessor;
            _DB = dB;
        }

        public UserClaimsModel CurrentUserInfo
        {
            get
            {
                UserClaimsModel obj = null;
                var user = httpContextAccessor.HttpContext.User;

                if (user != null)
                {
                    var userID = user.FindFirstValue(Gx._USERID_KEY).ToInt();
                    var loginUserType = Gx.GetEnumByValue<LoginUserType>(user.FindFirstValue(Gx._LOGIN_USER_TYPE_KEY).ToInt());
                    var loginTypeID = user.FindFirstValue(Gx._LOGIN_TYPE_ID_KEY).ToInt();

                    (bool, List<int>) userRoleDepartment = default;
                    (bool, List<int>) userKuangShanDepartment = default;
                    List<int> userWarehouseIDs = default;
                    List<int> userWarehouseIDsWithDataDepartment = default;
                    List<int> regulatorDepartmentIDs = default;

                    //获取用户所有角色中所有部门ID的集合
                    if (loginUserType == LoginUserType.集团)
                    {
                        userRoleDepartment = GetUserRoleDepartmentInfo(userID);
                        userKuangShanDepartment = GetUserKuangShanDepartmentInfo(userID);
                        userWarehouseIDs = GetUserWarehouseIDs(userID);
                        userWarehouseIDsWithDataDepartment = GetUserWarehouseIDsByDataDepartment(loginTypeID, userRoleDepartment.Item1, userRoleDepartment.Item2, loginTypeID);
                    }
                    else if (loginUserType == LoginUserType.监管部门)
                    {
                        regulatorDepartmentIDs = GetRegulatorDepartmentIDs(userID);
                    }
                    else
                    {
                        //throw new CustomException("登录时获取身份信息异常！");
                        return new UserClaimsModel {
                            //登录身份信息
                            LoginCode = "",
                            LoginUserType = LoginUserType.超级用户,
                            LoginTypeID = -1,

                            //用户信息
                            UserID = 1,
                            UserName = "超级管理员",
                        };
                    }

                    obj = new UserClaimsModel
                    {
                        //登录身份信息
                        LoginCode = user.FindFirstValue(Gx._LOGIN_CODE_KEY),
                        LoginUserType = Gx.GetEnumByValue<LoginUserType>(user.FindFirstValue(Gx._LOGIN_USER_TYPE_KEY).ToInt()),
                        LoginTypeID = user.FindFirstValue(Gx._LOGIN_TYPE_ID_KEY).ToInt(),

                        //用户信息
                        UserID = user.FindFirstValue(Gx._USERID_KEY).ToInt(),
                        UserName = user.FindFirstValue(Gx._USERNAME_KEY),

                        //扩展权限相关信息
                        LoginUserRoleDepartment = userRoleDepartment,
                        LoginUserKuangShanDepartment = userKuangShanDepartment,
                        LoginUserWarehouseIDs = userWarehouseIDs,
                        LoginUserWarehouseIDsWithDataDepartment = userWarehouseIDsWithDataDepartment,
                        LoginRegulatorDepartmentIDs = regulatorDepartmentIDs,
                    };
                }

                return obj;
            }
        }

        #region 获取用户角色对应部门的数据信息 GetUserRoleDepartmentInfo
        public (bool, List<int>) GetUserRoleDepartmentInfo(int userID)
        {
            //得到当前用户所有的角色IDs
            var roleIDs = _DB.Queryable<UserRole>().Where(x => x.UserID == userID).Select(x => x.RoleID).ToList();

            //得到角色的信息
            var roles = _DB.Queryable<Role>().Where(x => roleIDs.Contains(x.RoleID)).ToList();

            //如果这些角色中有选择的全部，则就是查全部数据
            if (roles.Any(x => x.DataPermissionType == (int)Role_DataPermission.全部))
            {
                return (true, null);
            }

            //否则，查询得到这些角色中设置的所有的部门ID集合
            var departmentIDs = _DB.Queryable<RoleDepartment>().Where(x => roleIDs.Contains(x.RoleID)).Select(x => x.DepartmentID).Distinct().ToList();

            return (false, departmentIDs);
        }
        #endregion

        #region 获取用户角色对应部门且部门类型为矿山的数据信息  GetUserKuangShanDepartmentInfo
        public (bool, List<int>) GetUserKuangShanDepartmentInfo(int userID)
        {
            //得到当前用户所有的角色IDs
            var roleIDs = _DB.Queryable<UserRole>().Where(x => x.UserID == userID).Select(x => x.RoleID).ToList();

            //得到角色的信息
            var roles = _DB.Queryable<Role>().Where(x => roleIDs.Contains(x.RoleID)).ToList();

            //如果这些角色中有选择的全部，则就是查全部数据
            if (roles.Any(x => x.DataPermissionType == (int)Role_DataPermission.全部))
            {
                return (true, null);
            }

            //否则，查询得到这些角色中设置的所有的部门ID集合
            var departmentIDs = _DB.Queryable<RoleDepartment>()
                .InnerJoin<Department>((rd, d) => rd.DepartmentID == d.DepartmentID)
                .Where((rd, d) => d.Type == (int)Department_Type.矿山 && roleIDs.Contains(rd.RoleID))
                .Select((rd, d) => rd.DepartmentID)
                .Distinct().ToList();

            return (false, departmentIDs);
        }
        #endregion

        #region 获取用户是哪个仓库管理员的仓库IDs  GetUserWarehouseIDs
        public List<int> GetUserWarehouseIDs(int userID)
        {
            return _DB.Queryable<WarehouseUser>().Where(x => x.UserID == userID).Select(x => x.WarehouseID).Distinct().ToList();
        }
        #endregion

        #region 获取监管部门用户应该有哪些矿山（部门）的IDs  GetRegulatorDepartmentIDs
        public List<int> GetRegulatorDepartmentIDs(int userID)
        {
            var regulatorUser = _DB.Queryable<RegulatorUser>().Where(x => x.RegulatorUserID == userID).First();
            if (regulatorUser.IsEmpty())
            {
                throw new CustomException("监管用户信息获取失败！");
            }

            var areaIDs = _DB.Queryable<RegulatorData>().Where(x => x.RegulatorID == regulatorUser.RegulatorID && x.AreaID != null).Select(x => x.AreaID).ToList();

            if (areaIDs.IsEmpty() || areaIDs.Count == 0)
            {
                throw new CustomException("请联系管理员完善数据权限后再进行登录！");
            }

            return _DB.Queryable<Department>().Where(x => x.Type == (int)Department_Type.矿山 && x.AreaID != null && areaIDs.Contains(x.AreaID)).Select(x => x.DepartmentID).ToList();
        }
        #endregion

        #region 根据模块+部门，获取相应的数据的主键ID，即数据归属的信息  GetTablePkIDs
        public List<int> GetTablePkIDs(DataDepartment_Type type, int? groupInfoID, int loginTypeID, params int[] departmentIDs)
        {
            var gid = groupInfoID.HasValue ? groupInfoID.Value : loginTypeID;
            return _DB.Queryable<DataDepartment>().Where(x => x.Type == (int)type && x.GroupInfoID == gid && (x.DepartmentID == Gx._NO_DATA_PERMISSION_VALUE || departmentIDs.Contains(x.DepartmentID)))
                .Select(x => x.DataID).Distinct().ToList();
        }
        #endregion

        #region 获取仓库IDs，根据用户的数据权限获取  GetUserWarehouseIDsByDataDepartment
        public List<int> GetUserWarehouseIDsByDataDepartment(int groupInfoID, bool isAll, List<int> departmentIDs, int loginTypeID)
        {
            if (isAll == true)
            {
                return _DB.Queryable<Warehouse>().Where(x => x.GroupInfoID == groupInfoID && x.IsDelete == false).Select(x => x.WarehouseID).ToList();
            }
            else
            {
                return GetTablePkIDs(DataDepartment_Type.仓库管理, groupInfoID, loginTypeID, departmentIDs.ToArray());
            }
        }
        #endregion
    }
}
